package com.changge.common.core.utils;

import com.changge.common.core.enums.CommonErrorCode;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.io.IOException;

/**
 * 请求响应工具类
 *
 * @author zhangrongkang
 * @since 2023/6/20
 */
@Slf4j
@Component
public class ServletUtil {

    /**
     * 获取当前线程请求
     *
     * @return request请求
     */
    public static HttpServletRequest getRequest() {
        return getRequestAttributes().getRequest();
    }

    /**
     * 获取当前线程响应
     *
     * @return request请求
     */
    public static HttpServletResponse getResponse() {
        return getRequestAttributes().getResponse();
    }

    /**
     * 设置Zip响应Servlet
     *
     * @param data zip数据
     */
    public static void setZipServletResponse(byte[] data) {
        HttpServletResponse response = getResponse();
        response.reset();
        response.addHeader("Access-Control-Allow-Origin", "*");
        response.addHeader("Access-Control-Expose-Headers", "Content-Disposition");
        response.setHeader("Content-Disposition", "attachment; filename=\"blog.zip\"");
        response.addHeader("Content-Length", "" + data.length);
        response.setContentType("application/octet-stream; charset=UTF-8");
        try {
            IOUtils.write(data, response.getOutputStream());
        } catch (IOException e) {
            log.error("打包Zip文件出错, e: {}", e.getMessage());
            // 抛出系统资源异常
            throw CommonErrorCode.SYSTEM_RESOURCE_EXCEPTION.exception();
        }
    }

    /**
     * 获取当前线程中的Servlet相关属性
     *
     * @return Servlet相关属性
     */
    private static ServletRequestAttributes getRequestAttributes() {
        return (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
    }
}
